<template>
  <div class="taskManage-page">
    <div class="taskManage-wrap">
      <!-- <div class="task-top">
          <el-radio-group
            v-model="tabPosition"
            @change="handleClick"
            style="margin-bottom: 30px"
          >
            <el-radio-button label="first">全部任务</el-radio-button>
            <el-radio-button label="second">下属任务</el-radio-button>
            <el-radio-button label="third">我发起的</el-radio-button>
            <el-radio-button label="fourth">我参与的</el-radio-button>
          </el-radio-group>
        </div> -->

      <div class="task-comment">
        <div class="search-from">
          <el-form
            :inline="true"
            :model="queryParams"
            class="demo-form-inline"
            id="queryParams"
          >
            <el-form-item>
              <el-input
                v-model.trim="queryParams.keyword"
                placeholder="请输入关键字"
                clearable
              />
            </el-form-item>
            <el-form-item>
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 260px"
                value-format="YYYY-MM-DD"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-select
                v-model="queryParams.status"
                placeholder="任务状态"
                clearable
              >
                <el-option
                  v-for="item in rsgl_task_status"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select
                v-model="queryParams.dealStatus"
                placeholder="操作状态"
                clearable
              >
                <el-option
                  v-for="item in rsgl_conduct_type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select v-model="queryParams.impSign" placeholder="紧要程度">
                <el-option
                  v-for="item in work_order_level"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item class="mr-15px">
              <el-tree-select
                v-model="queryParams.businessType"
                :data="workOrderType"
                placeholder="关联业务"
                default-expand-all
                style="width: 100%"
                clearable
                @change="changeBusinessType"
              />
            </el-form-item>
            <el-form-item
              class="mr-15px"
              v-if="queryParams.businessType != 10 && !isWeekView"
            >
              <el-select
                v-model.trim="queryParams.businessId"
                placeholder="业务名称"
                filterable
                remote
                :remote-method="querySearch"
                @focus="promptMsg"
                clearable
                style="width: 100%"
                v-if="showAuto"
              >
                <el-option
                  v-for="item in businessOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <!-- <el-autocomplete
                v-model="name"
                :fetch-suggestions="querySearch"
                clearable
                style="width: 100%"
                placeholder="业务名称"
                @select="valueChange"
                @change="valueChange"
                @focus="promptMsg"
                multiple
                v-if="showAuto"
              /> -->
              <el-input
                v-model="name"
                style="width: 100%"
                placeholder="业务名称"
                clearable
                v-else-if="queryParams.businessType == 8"
                @change="changeId"
                @focus="promptMsg"
              ></el-input>
              <el-select
                v-model.trim="queryParams.businessId"
                placeholder="业务名称"
                filterable
                remote
                :remote-method="queryProject"
                @change="changeBusinessId"
                @focus="promptMsg"
                clearable
                style="width: 100%"
                v-else
              >
                <el-option
                  v-for="item in optionsProjectName"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item class="mr-15px">
              <el-select
                v-model="queryParams.severity"
                placeholder="严重状态"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="item in task_severity"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery" icon="Search"
                >查询</el-button
              >
              <el-button type="default" @click="resetQuery" icon="Refresh"
                >重置</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <div class="flex">
          <div>
            <el-button type="primary" @click="addItem" icon="Plus"
              >添加</el-button
            >
            <el-button @click="statistics" icon="MagicStick">统计</el-button>

            <el-button icon="StarFilled" @click="showTaskConfig" v-if="role"
              >项目配置</el-button
            >
          </div>
          <right-toolbar
            v-model:showSearch="showSearch"
            :search="false"
            @queryTable="getList"
            :columns="columns"
          ></right-toolbar>
        </div>
        <el-table
          border
          stripe
          v-loading="loading"
          @selection-change="handleSelectionChange"
          :data="tableData"
          style="margin-top: 18px"
          @row-dblclick="handleClickProject"
          :cell-class-name="setWarning"
        >
          <!-- <el-table-column type="selection" width="55" /> -->
          <el-table-column
            type="index"
            width="55"
            label="序号"
            align="center"
          />

          <el-table-column
            prop="title"
            label="任务标题"
            :show-overflow-tooltip="true"
            align="center"
            v-if="columns[0].visible"
          >
            <template v-slot="scope">
              <div style="text-align: left; min-width: 220px">
                {{ scope.row.title }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="businessType"
            label="任务类型"
            align="center"
            width="100"
            v-if="columns[1].visible"
          >
            <template v-slot="scope">
              <div>
                {{
                  task_order_type.find(
                    item => item.value == scope.row.businessType
                  )
                    ? task_order_type.find(
                        item => item.value == scope.row.businessType
                      ).label
                    : '--'
                }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="director"
            label="负责人"
            align="center"
            width="90"
            v-if="columns[2].visible"
          />
          <el-table-column
            label="任务状态"
            prop="status"
            align="center"
            width="90"
            v-if="columns[3].visible"
          >
            <template v-slot="scope">
              <div
                style="font-size: 12px"
                :class="
                  scope.row.status == '1'
                    ? 'orange-color'
                    : scope.row.status == '3'
                    ? 'green-color'
                    : scope.row.status == '5'
                    ? 'red-color'
                    : scope.row.status == '4'
                    ? 'blue-color'
                    : ''
                "
              >
                {{
                  rsgl_task_status.find(item => item.value == scope.row.status)
                    ? rsgl_task_status.find(
                        item => item.value == scope.row.status
                      ).label
                    : '--'
                }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="父任务"
            prop="parentIdCn"
            align="center"
            v-if="columns[4].visible"
          ></el-table-column>
          <el-table-column
            label="业务名称"
            prop="businessName"
            align="center"
            v-if="columns[11].visible"
          ></el-table-column>
          <el-table-column
            label="操作状态"
            prop="dealStatus"
            width="200"
            align="center"
            v-if="columns[5].visible"
          >
            <template v-slot="scope">
              <div style="font-size: 12px">
                <span
                  style="font-family: '微软雅黑', sans-serif; margin-right: 5px"
                  :class="
                    scope.row.dealStatus == '1' ||
                    scope.row.dealStatus == '0' ||
                    scope.row.dealStatus == '9' ||
                    scope.row.dealStatus == '12' ||
                    scope.row.dealStatus == '13'
                      ? 'orange-color'
                      : scope.row.dealStatus == '5'
                      ? 'green-color'
                      : scope.row.dealStatus == '3'
                      ? 'red-color'
                      : scope.row.dealStatus == '2' ||
                        scope.row.dealStatus == '4'
                      ? 'blue-color'
                      : ''
                  "
                  >●</span
                >
                {{
                  dealStatusList.find(item => item.id == scope.row.dealStatus)
                    ? dealStatusList.find(
                        item => item.id == scope.row.dealStatus
                      ).name
                    : '--'
                }}
                <span v-show="scope.row.diffTime"
                  >({{ scope.row.diffTime }})</span
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="impSign"
            label="紧要程度"
            align="center"
            width="80"
            v-if="columns[6].visible"
          >
            <template v-slot="scope">
              <div>
                {{
                  work_order_level.find(item => item.value == scope.row.impSign)
                    ? work_order_level.find(
                        item => item.value == scope.row.impSign
                      ).label
                    : '--'
                }}
              </div>
            </template>
          </el-table-column>

          <el-table-column
            prop="severity"
            label="严重程度"
            align="center"
            width="170"
            v-if="columns[7].visible"
          >
            <template v-slot="scope">
              <span>{{
                task_severity.find(v => v.value === scope.row.severity)?.label
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="beginTime"
            label="创建时间"
            align="center"
            width="170"
            v-if="columns[8].visible"
          >
            <template v-slot="scope">
              <span>{{ scope.row.beginTime }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="startTime"
            label="开始时间"
            align="center"
            width="170"
            v-if="columns[9].visible"
          >
            <template v-slot="scope">
              <span>{{ scope.row?.startTime }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="endTime"
            label="期望完成时间"
            align="center"
            width="170"
            v-if="columns[10].visible"
          >
            <template v-slot="scope">
              <span>{{ scope.row?.endTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template v-slot="scope">
              <el-button
                v-if="
                  scope.row.dealStatus === '13' ||
                  scope.row.dealStatus === '0' ||
                  (scope.row.dealStatus === '9' && scope.row.status === '1')
                "
                type="primary"
                @click="toDispose(scope.row)"
                plain
                icon="CircleCheck"
                size="small"
              >
                处理</el-button
              >
              <el-button
                v-else
                type="primary"
                plain
                disabled
                icon="CircleCheck"
                size="small"
              >
                处理</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="() => getList()"
        />
      </div>
    </div>
    <TaskLeaderConfig
      v-model:showConfigModal="showConfigModal"
      :projectList="projectList"
      @queryList="queryList"
    />
  </div>
</template>

<script setup name="TaskManage">
import {
  getTaskList,
  getProjectNodeList,
  editProjectNode,
  delProjectNode,
  getOrdpurchaseorder,
  getOrdinnerorder,
  getBusinessName
} from '@/api/taskManage/task'
import { getOrdprojectNoPriv } from '@/api/projectManage/project' //项目模糊搜索
import { getOrderList } from '@/api/salesManage/contractManage' //订单模糊搜索
import { getListByCustomerName } from '@/api/customerManage/customerList' //企业客户模糊搜索
import { getBusinessOpportunityListSelect } from '@/api/salesManage/businessManage' //商机模糊搜索
import { getDetailTactlistByCactName } from '@/api/customerManage/customerList' //客户详情

import { useRoute, useRouter } from 'vue-router'
import useCommonStore from '@/store/modules/common'
import useUserStore from '@/store/modules/user'
import { computed, getCurrentInstance, reactive, toRefs } from 'vue'
import TaskLeaderConfig from '../modules/taskLeaderConfig.vue'
import { format, startOfMonth, endOfMonth } from 'date-fns'
const { proxy } = getCurrentInstance()
// 通用数据store
const router = useRouter()
const route = useRoute()
const commonStore = useCommonStore()
const userStore = useUserStore()

const role = computed(
  () =>
    userStore.roles.indexOf('task_manager') > -1 ||
    userStore.roles.indexOf('admin') > -1
)
const {
  work_order_level,
  rsgl_task_status,
  rsgl_conduct_type,
  task_order_type, //任务类型
  system_or_project_name,
  task_severity,
  reminder_opening
} = proxy.useDict(
  'work_order_level',
  'rsgl_task_status',
  'rsgl_conduct_type',
  'task_order_type',
  'system_or_project_name',
  'task_severity',
  'reminder_opening'
)
const data = reactive({
  loading: false,
  isAdd: false,
  sortObj: null,
  tableData: null,
  // 总条数
  total: 0,
  // 日期范围
  dateRange: [],
  // 选中数组
  ids: [],
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  dealStatusList: [
    {
      id: '0',
      name: '待处理'
    },
    {
      id: '1',
      name: '已发起'
    },
    {
      id: '2',
      name: '已分配'
    },
    {
      id: '3',
      name: '已退回'
    },
    {
      id: '4',
      name: '转他人处理'
    },
    {
      id: '5',
      name: '已完结'
    },
    {
      id: '6',
      name: '已撤销'
    },
    {
      id: '7',
      name: '进度更新'
    },
    {
      id: '8',
      name: '结果反馈'
    },
    {
      id: '9',
      name: '处理中'
    },
    {
      id: '10',
      name: '结果反馈'
    },
    {
      id: '11',
      name: '修改任务'
    },
    {
      id: '12',
      name: '待研发处理'
    },
    {
      id: '13',
      name: '待确认'
    }
  ],
  // 显示搜索条件
  queryParams: {
    // keyword: null, // 名称
    // dealStatus: null, //任务状态
    // impSign: undefined, //紧要程度
    // businessType: '', //关联业务
    // businessId: null, //业务ID
    // belongId: null, //归属人ID
    pageNum: 1,
    pageSize: 10
  }
})
const {
  dealStatusList,
  tableData,
  total,
  dateRange,
  queryParams,
  isAdd,
  loading,
  sortObj,
  // 选中数组
  ids,
  // 非单个禁用
  single,
  // 非多个禁用
  multiple
  // 显示搜索条件
} = toRefs(data)

const tabPosition = ref('first')

const showSearch = ref(true)
const columns = reactive([
  { key: 0, label: '任务标题', visible: true },
  { key: 1, label: '任务类型', visible: true },
  { key: 2, label: '负责人', visible: true },
  { key: 3, label: '任务状态', visible: true },
  { key: 4, label: '父任务', visible: true },
  { key: 5, label: '操作状态', visible: true },
  { key: 6, label: '紧要程度', visible: true },
  { key: 7, label: '严重程度', visible: false },
  { key: 8, label: '创建时间', visible: true },
  { key: 9, label: '开始时间', visible: false },
  { key: 10, label: '期望完成时间', visible: false },
  { key: 11, label: '业务名称', visible: true }
])

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}
/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10
  }
  if (workId.value) {
    workId.value = ''
  }
  dateRange.value = []
  getList()
}
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

function refreshList() {
  getList()
}
//新增
function addItem() {
  router.push({
    path: '/rsgl/other/addTasking',
    query: { flag: 'add' }
  })
}
// 前往统计页面
function statistics() {
  router.push({
    path: '/tjfx/taskStatistics'
  })
}
//处理
function toDispose(row) {
  router.push({
    path: '/rsgl/other/taskProcessing',
    query: { id: row.id, operateId: row.operateId }
  })
}
// 双击列表 查看详情
const handleClickProject = row => {
  router.push({
    path: '/rsgl/other/taskDetails',
    query: { id: row.id, operateId: row.operateId }
  })
}
//详情
function toDetails(row) {
  router.push({
    path: '/rsgl/other/taskDetails',
    query: { id: row.id, operateId: row.operateId }
  })
}
//升序/降序
function sortChange(column) {
  var orderBy = ''
  if (column) {
    if (column.order === 'ascending') {
      //这里双重判断：该字段为升序时向后端传递升序参数，反之降序
      orderBy = column.prop + ' asc'
    } else if (column.order === 'descending') {
      orderBy = column.prop + ' desc'
    }
    sortObj.value = orderBy
    // getList(orderBy)
  }
}

//获取列表数据

function getList() {
  loading.value = true
  let param = { ...queryParams.value }
  if (workId.value) {
    param.workId = workId.value
  }
  param.startTime = dateRange.value != null ? dateRange.value[0] : ''
  param.endTime = dateRange.value != null ? dateRange.value[1] : ''
  getTaskList(param)
    .then(response => {
      if (response.code == 200) {
        tableData.value = response.rows
        total.value = response.total
        loading.value = false
      } else {
        loading.value = false
      }
    })
    .finally(() => {
      if (!workOrderType.value.length) {
        workOrderType.value = arrayToTree(task_order_type.value)
      }
    })
}

// 关联业务 关联名称

const optionsProjectName = ref({})
function promptMsg() {
  if (!queryParams.value.businessType) {
    optionsProjectName.value = []
    proxy.$modal.msgWarning('请先选择关联业务')
    return
  }
}
const businessOptions = ref([])
// 远程检索
async function querySearch(val) {
  const dataList = await getBusinessName({
    businessName: val || ''
  })
  if (dataList.code === 200) {
    businessOptions.value = (dataList.data || []).map(v => ({
      label: v.businessName,
      value: v.businessId
    }))
  }
}
const createFilter = queryString => {
  return restaurant => {
    return restaurant.businessName.indexOf(queryString) !== -1
  }
}

function changeId(val) {
  queryParams.value.businessId = val
  getList()
}

//关联项目类型
function changeBusinessId(val) {
  queryParams.value.businessId = optionsProjectName.value.find(
    item => item.value == val
  )?.value
  getList()
}
// 判断是否选择研发
const showAuto = computed(() => {
  // return queryParams.value.businessType.indexOf(workOrderType.value) < 0
  if (queryParams.value.businessType) {
    // 研发子内容
    const findResult = workOrderType.value
      .find(v => v.value == 9)
      .children.find(v => v.value == queryParams.value.businessType)
    return findResult
  } else {
    return false
  }
})
//关联项目名称
async function queryProject(val) {
  optionsProjectName.value = []
  switch (queryParams.value.businessType) {
    case '1': //项目
      const proList = await getOrdprojectNoPriv({
        proName: val,
        pageSize: 20
      })

      if (proList.code === 200) {
        optionsProjectName.value = (proList.rows || []).map(v => ({
          label: v.proName,
          value: v.projectId
        }))
      }
      break
    case '2':
      const orderList = await getOrderList({
        title: val,
        pageSize: 20
      })

      if (orderList.code === 200) {
        optionsProjectName.value = (orderList.rows || []).map(v => ({
          label: v.title,
          value: v.id
        }))
      }
      break
    case '3': //客户
      const customerList = await getListByCustomerName({
        customer: val,
        pageSize: 20
      })

      if (customerList.code === 200) {
        optionsProjectName.value = (customerList.data || []).map(v => ({
          label: v.customerName,
          value: v.id
        }))
      }
      break
    case '4': //商机
      optionsProjectName.value = []
      const businessList = await getBusinessOpportunityListSelect({
        keyword: val,
        pageSize: 100,
        pageNum: 1
      })

      if (businessList.code === 200) {
        optionsProjectName.value = (businessList.rows || []).map(v => ({
          label: v.titleName,
          value: v.id
        }))
      }
      break
    case '5': //联系人
      optionsProjectName.value = []
      const contactsNameList = await getDetailTactlistByCactName({
        pageSize: 20,
        entId: '',
        contactName: val
      })

      if (contactsNameList.code === 200) {
        optionsProjectName.value = (contactsNameList.data || []).map(v => ({
          label: v.contactName,
          value: v.id
        }))
      }
      break
    case '6': //采购订单
      optionsProjectName.value = []
      const ordpurchaseorderList = await getOrdpurchaseorder({
        title: val,
        pageSize: 20
      })
      if (ordpurchaseorderList.code === 200) {
        optionsProjectName.value = (ordpurchaseorderList.rows || []).map(v => ({
          label: v.title,
          value: v.id
        }))
      }
      break
    case '7': //内部订单
      optionsProjectName.value = []
      const ordinonerorderList = await getOrdinnerorder({
        title: val,
        pageSize: 20
      })

      if (ordinonerorderList.code === 200) {
        optionsProjectName.value = (ordinonerorderList.rows || []).map(v => ({
          label: v.title,
          value: v.id
        }))
      }
      break
  }
}

// 选择关联业务
function changeBusinessType(val) {
  // 清空业务名称搜选项
  queryParams.value.businessNames = ''
  queryParams.value.businessId = ''
  optionsProjectName.value = []
  getList()
}

const workOrderType = ref([])
/**
 * @params arr 输入数组
 * @params nodeKey 树唯一标识
 * @params parentId 父id
 *
 */
function arrayToTree(arr, nodeKey = 'value', parentId = 'parentId') {
  const mapObj = new Map()
  const result = []
  arr.forEach(v => {
    mapObj.set(v.value, v)
  })
  for (const [key, val] of mapObj) {
    if (val.parentId && mapObj.has(val.parentId)) {
      if (!mapObj.get(val.parentId).children) {
        mapObj.get(val.parentId).children = []
      }
      const some = mapObj.get(val.parentId).children.some(v => {
        return v.value === val.value
      })
      if (!some) {
        mapObj.get(val.parentId).children.push(val)
      }
    } else {
      result.push(mapObj.get(key))
    }
  }
  return result
}

// 父任务远程检索
const options = ref([])
const lists = ref([])
function remoteMethod(query) {
  if (query) {
    loading.value = true
    const timer = setTimeout(() => {
      loading.value = false
      options.value = lists.value.filter(item => {
        return item.label.toLowerCase().includes(query.toLowerCase())
      })
      clearTimeout(timer)
    }, 200)
  } else {
    options.value = []
  }
}

const showConfigModal = ref(false)
// 负责人配置
const projectList = ref([])
function showTaskConfig() {
  if (!projectList.value.length) {
    queryList()
  }
  showConfigModal.value = true
}

function queryList() {
  getProjectNodeList().then(res => {
    projectList.value = res.data
  })
}

onActivated(() => {
  queryList()
})

/**
 * 初始化
 */
const workId = ref('')
async function init() {
  if (route.query.id) {
    workId.value = route.query.id
  }
  getList()
  queryList()
}
init()

// 设置单元格样式
function setWarning({ row, column, rowIndex, columnIndex }) {
  if (columnIndex === 1 && row.status != 3) {
    if (row.endTime && row.warning) {
      const deadline = new Date(
        row.endTime.replace(/\d\d:\d\d:\d\d/, '00:00:00')
      ).getTime()
      const day = [0, 1, 3, 5, 7]
      const now = new Date(format(new Date(), 'yyyy-MM-dd 00:00:00')).getTime()
      const warningDay = day[row.warning]
      if (deadline - now <= warningDay * 24 * 60 * 60 * 1000) {
        return 'warning-cell'
      } else {
        return ''
      }
    } else {
      return 'warning-cell'
    }
  }
  return ''
}
</script>

<style lang="scss" scoped>
.taskManage-page {
  padding: 20px 18px;
  display: block;
  .orange-color {
    color: #f59a23;
  }
  .blue-color {
    color: #409efc;
  }
  .green-color {
    color: #4bd863;
  }
  .red-color {
    color: red;
  }
  #queryParams {
    :deep .el-input__wrapper {
      // width: 200px;
      @apply w-200px;
    }
    :deep .el-form-item {
      margin-right: 10px;
    }
  }
  .taskManage-wrap {
    background: #fff;
    display: block;
    border-radius: 10px;
    border: 1px solid #eee;
    // -moz-box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.15);
    // -webkit-box-shadow: 0px 0px 5px rgb(0 0 0 / 0.15);
    // box-shadow: 0px 0px 5px rgb(0 0 0 / 0.15);
    .task-top {
      border-bottom: 1px solid #eee;
      padding: 18px;
      height: 65px;
    }
    .task-comment {
      padding: 18px;
    }
  }
  ::v-deep .warning-cell {
    background-color: rgba(254, 200, 5, 0.1) !important;
    // color: white;
  }
}
</style>
